var url = "http://127.0.0.1:8083/";

function getCookie(key){
    var cookie = document.cookie;
    var s = cookie.replace("; ","=");
    while (s.indexOf(";") != -1){
        s = s.replace("; ","=");
    }
    var strings = s.replace("; ","=").split("=");
    if (strings.indexOf(key) == -1){
        return null;
    }
    return strings[strings.indexOf(key) + 1].trim();
}
function toPage(pageName) {
$.ajax({
    url:url + "user/"+pageName,
    type:"GET",
    async:false,
    success:function (data) {
        if (data["code"] == 200 || data["code"] == 204) {
            window.location.href=url + "user" + data["data"]+".html";
        }
    }
})
}

function write(obj,newListElement){
    var product = $(obj).find(".single-product-item");
    let a_image = product.find(".single-product-img").find("a");
    var price = product.find(".new-price");
    var name = product.find("h3").find("a");
    var modal = product.find(".modal-view");

    a_image.attr("data-target", newListElement["productId"]);
    product.find(".primary-image").attr("src",newListElement["productPicture"]);
    price.text("￥" + newListElement["productPrice"]);
    name.html(newListElement["productName"]);
    modal.attr("title",newListElement["productId"]);
}

window.onload=function () {
    //跳转到收藏
    $(".header-area .account-usd .submenu-mainmenu .my-like").click(function () {
        $.ajax({
            url: url + "collection/toCollection",
            type: "POST",
            data: {userName: getCookie("USER_NAME")},
            success: function (data) {
                window.location.href=url + "user/" + data["data"] + ".html";
            }
        });
    });

    //跳转到订单
    $(".header-area .account-usd .submenu-mainmenu .my-order").click(function () {
        $.ajax({
            url: url + "order/toOrder",
            type: "POST",
            data: {userName: getCookie("USER_NAME")},
            success:function (data) {
                window.location.href=url + "user/" + data["data"] + ".html";
            }
        });
    });

    //查找商品
    $(function () {
        $(".header-area .search-box .search-pro").click(function () {
            $.ajax({
                url: url + "user/setKeyWord",
                type: "POST",
                data: {keyWord:$(this).prev().val()},
                success: function (data) {
                    if (data["code"] == 200) {
                        window.location.href=url + "user/" + data["data"] + ".html";
                    }
                }
            })
        });
    });

    $.ajax({
        url: url + "cart/getCartList",
        type: "POST",
        data: {userName: getCookie("USER_NAME")},
        success: function (data) {
            if (data["code"] == 200) {
                var datum = data["data"];
                var sum = 0;
                for (let i = 0; i < datum.length; i++) {
                    var product = datum[i]["product"];
                    $(".header-area .top-right .cart .mycart #check-box").before(
                        "<li class=\"single-cart-item clearfix\">\n" +
                        "    <span class=\"cart-img\">\n" +
                        "        <a href=\"javascript:void(0);\" class='show-info' data-target='" + product["productId"] + "'><img src=\"" + product["productPicture"] + "\" alt=\"\" width=\"50\"></a>\n" +
                        "    </span>\n" +
                        "    <span class=\"cart-info\">\n" +
                        "        <a href=\"javascript:void(0);\" class='show-info' data-target='\" + product[\"productId\"] + \"'>" + product["productName"] + "</a>\n" +
                        "        <span>￥<span>" + product["productPrice"] + "</span> x <span>" + datum[i]["carCount"] + "</span></span>\n" +
                        "    </span>\n" +
                        "</li>"
                    );

                    sum += product["productPrice"] * datum[i]["carCount"];
                }
                $(".cart #product_count").html(datum.length);
                $(".cart #amount").html("￥" + sum.toFixed(2));
            }
        }
    });

    //品牌显示
    $(function () {
        let $img = $(".owl-wrapper-outer .owl-wrapper .owl-item .single-client img");
        $.ajax({
            url: url + "getBrand",
            type: "GET",
            async: false,
            success: function (data) {
                let datum = data["data"];
                var i = 0;
                $img.each(function () {
                    let datumElement = datum[i++];
                    this.src = datumElement["brandPicture"];
                    $(this).attr("alt", datumElement["brandName"]);
                })
            }
        })
    });

    //登录成功显示姓名和购物车，否则不显示
    $(function () {
        var username = getCookie("USER_NAME");
        if (username != null && username != '') {
            let $nav = $("#nav-header");
            $nav.find("li").removeClass("welcome");
            $nav.find(".hidden-xs").first().attr("class", "hidden-xs welcome");
            $nav.find(".user").html("欢迎 ：<a href='#'>" + username + "</a>!");
            let cart_li = $nav.find(".cart");
            cart_li.find(".mycart").css("display", "block");
            cart_li.find("ul").last().css("display", "none");
        }
    });

    //退出登录
    $("a[class='log-out']").click(function () {
        $.ajax({
            url: url + "user/logout",
            type: "POST",
            data: {cookieName: "USER_NAME"},
            success: function (data) {
                toPage(data["data"]);
            }
        })
    });

    //商品数量加减
    $(".cart .numbers-row .reduce").click(function () {
        var $count = $(this).parent().next(".count");
        if (parseInt($count.val()) <= 1) {
            $count.val(1);
        } else {
            $count.val(parseInt($count.val()) - 1);
        }
    });
    $(".cart .numbers-row .add").click(function () {
        var $count = $(this).parent().prev(".count");
        $count.val(parseInt($count.val()) + 1);
    });

    //设置默认数量为1
    $(".cart .numbers-row .count").blur(function () {
        var $count = $(".cart .numbers-row .count");

        if ($count.val() == null || $count.val() == '') {
            $count.val(1);
            $count.attr("disabled", "disabled");
        } else {
            $count.removeAttr("disabled");
        }
    });

    //获取新品商品
    $(getnew());
    $(".new").click(getnew());

    function getnew() {
        $.ajax({
            url: url + "user/new",
            type: "POST",
            async: false,
            success: function (data) {
                var newList = data["data"];
                var i = 0;
                let $new = $("#new .tab-item-slider div.col-xs-12");
                $new.each(function () {
                    var newListElement = newList[i++];
                    write(this,newListElement);
                })
            }
        });

    }

    //获取精选商品
    $(".featured").click(getselect());

    function getselect() {
        $.ajax({
            url: url + "user/select",
            type: "POST",
            async: false,
            success: function (data) {
                var newList = data["data"];
                var i = 0;
                let $new = $("#featured .tab-item-slider div.col-xs-12");
                $new.each(function () {
                    var newListElement = newList[i++];
                    write(this,newListElement);
                })
            }
        });

    }

    //获取畅销商品
    $(".best").click(getbestSell());

    function getbestSell() {
        $.ajax({
            url: url + "/user/bestSell",
            type: "POST",
            async: false,
            success: function (data) {
                var newList = data["data"];
                var i = 0;
                let $new = $("#best .tab-item-slider div.col-xs-12");
                $new.each(function () {
                    var newListElement = newList[i++];
                    write(this,newListElement);
                })
            }
        });

    }

    //点击图片及连接显示详情
    $(".single-product-item .single-product-img").find("a").click(function () {
        $.ajax({
            url:url + "user/setDetails",
            type:"POST",
            data:{id:$(this).attr("data-target")},
            success:function (data) {
                if (data["code"] == 200){
                    toPage("productDetails");
                }
            }
        })
    });


    //点击显示详情页
    $("a.modal-view").click(function () {
        var id = $(this).parent().parent().parent().parent().find("a");
        $.ajax({
            url:url + "user/showProduct",
            type: "POST",
            data:{productId:id.attr("data-target")},
            success:function (data) {
                if (data["code"] == 200) {
                    var $product = $(".modal-content .modal-body .modal-product");
                    var product_info = $product.find(".product-info");
                    var img = $product.find(".product-images").find(".main-image").find("img");
                    var price = product_info.find(".price-box").find(".price").find(".amount");
                    var remain = product_info.find(".product-detail").find(".remain");
                    var sales = product_info.find(".product-detail").find(".sales");
                    var desc = product_info.find(".quick-desc");
                    var name = product_info.find("h1");
                    var pid = product_info.find(".quick-add-to-cart").find(".cart").find("#pid");

                    var datum = data["data"];
                    var product = datum["product"];
                    var productInfo = datum["productInfo"];
                    var productSales = datum["productSales"];

                    $(img).attr("src",product["productPicture"]);
                    $(price).val("￥" + product["productPrice"]);
                    $(remain).text(product["inventoryRemain"]);
                    $(sales).text(productSales["salesCount"]);
                    $(desc).html(productInfo["productInfoIntroduction"]);
                    $(name).text(product["productName"]);
                    $(pid).val(product["productId"]);
                }
            }
        })
    });

    $(getWomen());
    $(getWomenTwo());
    $(getMen());
    $(getMenTwo());
    $(getAcc());
    $(getAccTwo());
    function getWomen() {
        $.ajax({
            url:url + "user/fashion",
            type: "POST",
            async:false,
            data:{primaryId:1},
            success:function (data) {
                if (data["code"] == 200) {
                    var women = data["data"];
                    var i = 0;
                    var $women = $(".trend_content #women .trend-item-slider div.col-xs-12");
                    $women.each(function () {
                        write(this,women[i++]);
                    })
                }
            }
        })
    }

    function getMen() {
        $.ajax({
            url:url + "user/fashion",
            type: "POST",
            async:false,
            data:{primaryId:2},
            success:function (data) {
                if (data["code"] == 200) {
                    var men = data["data"];
                    var i = 0;
                    var $men = $(".trend_content #men .trend-item-slider div.col-xs-12");
                    $men.each(function () {
                        write(this,men[i++]);
                    })
                }
            }
        });
    }

    function getAcc() {
        $.ajax({
            url:url + "user/fashion",
            type: "POST",
            async:false,
            data:{primaryId:3},
            success:function (data) {
                if (data["code"] == 200) {
                    var acc = data["data"];
                    var i = 0;
                    var $acc = $(".trend_content #acc-two .trend-item-slider div.col-xs-12");
                    $acc.each(function () {
                        write(this,acc[i++]);
                    })
                }
            }
        });
    }

    function getWomenTwo() {
        $.ajax({
            url:url + "user/sell",
            type: "POST",
            async:false,
            data:{primaryId:1},
            success:function (data) {
                if (data["code"] == 200) {
                    var women = data["data"];
                    var i = 0;
                    var $women = $(".trend_content #women-two .trend-item-slider div.col-xs-12");
                    $women.each(function () {
                        write(this,women[i++]);
                    })
                }
            }
        });
    }

    function getMenTwo() {

        $.ajax({
            url:url + "user/sell",
            type: "POST",
            async:false,
            data:{primaryId:2},
            success:function (data) {
                if (data["code"] == 200) {
                    var men = data["data"];
                    var i = 0;
                    var $men = $(".trend_content #men-two .trend-item-slider div.col-xs-12");
                    $men.each(function () {
                        write(this,men[i++]);
                    })
                }
            }
        });
    }

    function getAccTwo() {
        $.ajax({
            url:url + "user/sell",
            type: "POST",
            async:false,
            data:{primaryId:3},
            success:function (data) {
                if (data["code"] == 200) {
                    var acc = data["data"];
                    var i = 0;
                    var $acc = $(".trend_content #acc-two .trend-item-slider div.col-xs-12");
                    $acc.each(function () {
                        write(this,acc[i++]);
                    })
                }
            }
        });}
};

function toWomenShop(){
    $.ajax({
        url: url + "user/setPrimary",
        type:"POST",
        async: false,
        data:{primaryId: 1},
        success:function (data) {
            if (data["code"] == 200) {
                toPage("shop");
            }
        }
    });
}

function toMenShop(){
    $.ajax({
        url: url + "user/setPrimary",
        type:"POST",
        async: false,
        data:{primaryId: 2},
        success:function (data) {
            if (data["code"] == 200) {
                toPage("shop");
            }
        }
    });
}

$("a.to-women-shop").click(function () {
    $.ajax({
        url: url + "user/setPrimary",
        type:"POST",
        async: false,
        data:{primaryId: 1},
        success:function (data) {
            if (data["code"] == 200) {
                toPage("shop");
            }
        }
    });
});
$("a.to-men-shop").click(function () {
    $.ajax({
        url: url + "user/setPrimary",
        type:"POST",
        async: false,
        data:{primaryId: 2},
        success:function (data) {
            if (data["code"] == 200) {
                toPage("shop");
            }
        }
    });
});
$("a.to-acc-shop").click(function () {
    $.ajax({
        url: url + "user/setPrimary",
        type:"POST",
        async: false,
        data:{primaryId: 3},
        success:function (data) {
            if (data["code"] == 200) {
                toPage("shop");
            }
        }
    });
});


